{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3f1e45d4",
   "metadata": {},
   "source": [
    "# 01 Vector Add\n",
    "向量加法 Kernel 示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a11d88d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "z[:5] = tensor([ 0.0413, -1.5824, -1.0520, -0.7632, -1.0360], device='cuda:0')\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import triton\n",
    "import triton.language as tl\n",
    "\n",
    "@triton.jit\n",
    "def vector_add_kernel(X_ptr, Y_ptr, Z_ptr, N: tl.constexpr):\n",
    "    pid = tl.program_id(0)\n",
    "    if pid < N:\n",
    "        tl.store(Z_ptr + pid, tl.load(X_ptr + pid) + tl.load(Y_ptr + pid))\n",
    "\n",
    "N = 1024\n",
    "x = torch.randn(N, device='cuda')\n",
    "y = torch.randn(N, device='cuda')\n",
    "z = torch.empty_like(x)\n",
    "vector_add_kernel[(N,)](x, y, z, N=N)\n",
    "print(\"z[:5] =\", z[:5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5661676b-4739-423e-89db-fe10e0455521",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0rc1"
  },
  "title": "Vector Add"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
